package com.keyboardr.gamerater;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.ActionMode;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.EditText;
import android.widget.ListView;

public class PlayersFragment extends ListFragment implements
		OnItemLongClickListener {
	private ActionMode mCurrentActionMode;

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		inflater.inflate(R.menu.players, menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.about:
			Intent intent = new Intent(Intent.ACTION_SEND);
			intent.setType("message/rfc882");
			intent.putExtra(Intent.EXTRA_EMAIL,
					new String[] { getString(R.string.dev_email) });
			intent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.app_name)
					+ " app");
			startActivity(intent);
			return true;
		}
		return false;
	}

	long lastId = -1;
	int lastGroupSize = -1;

	@Override
	public void onCreate(Bundle bundle) {
		super.onCreate(bundle);
		if (bundle != null) {
			lastId = bundle.getLong("selectedPlayer", -1);
			lastGroupSize = bundle.getInt("lastGroupSize", -1);
		}
		setHasOptionsMenu(true);

	}

	@Override
	public void onStart() {
		super.onStart();
		setListAdapter(new PlayerAdapter((RaterActivity) getActivity()));
		getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);

		if (lastId >= 0
				&& lastGroupSize == ((RaterActivity) getActivity())
						.getSelectedGroup().getPlayers().size()) {
			Player selected = ((RaterActivity) getActivity())
					.getSelectedGroup().getPlayers().get((int) lastId);
			if (selected != null) {
				int index = ((RaterActivity) getActivity()).getSortedList()
						.indexOf(selected);
				((ListFragment) getFragmentManager().findFragmentByTag(
						"players")).getListView().setItemChecked(index, true);
			}
		}
		if (RaterActivity.isHolo) {
			getListView().setOnItemLongClickListener(this);
		} else {
			registerForContextMenu(getListView());
		}
	}

	@Override
	public void onSaveInstanceState(Bundle bundle) {
		int position = getListView().getCheckedItemPosition();
		long id = getListView().getItemIdAtPosition(position);
		bundle.putLong("selectedPlayer", id);
		bundle.putInt("lastGroupSize", ((RaterActivity) getActivity())
				.getSelectedGroup().getPlayers().size());
	}

	@Override
	public void onListItemClick(ListView l, View v, int position, long id) {
		if (RaterActivity.isHolo) {
			boolean isSame = ((GamesFragment) getFragmentManager()
					.findFragmentByTag("games")).getFilter() == (Player) getListAdapter()
					.getItem(position);
			((GamesFragment) getFragmentManager().findFragmentByTag("games"))
					.setFilter((Player) getListAdapter().getItem(position));
			if (isSame) {
				clearSelection();
			}

		}
	}

	public void clearSelection() {
		getListView().setItemChecked(-1, true);
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		getActivity().getMenuInflater().inflate(R.menu.players_context, menu);
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		if (item.getItemId() == R.id.edit_player_name) {
			int position = ((AdapterView.AdapterContextMenuInfo) item
					.getMenuInfo()).position;
			Player player = (Player) getListAdapter().getItem(position);
			showEditPlayerDialog(player);
			return true;
		}
		return false;
	}

	@Override
	public boolean onItemLongClick(AdapterView<?> parent, View view,
			int position, long id) {
		final int pos = position;
		final Player player = (Player) getListAdapter().getItem(position);
		if (mCurrentActionMode != null) {
			return false;
		}

		mCurrentActionMode = getActivity().startActionMode(
				new ActionMode.Callback() {

					@Override
					public boolean onCreateActionMode(ActionMode mode, Menu menu) {
						mode.setTitle(player.toString());
						MenuInflater inflater = mode.getMenuInflater();
						inflater.inflate(R.menu.players_context, menu);
						return true;
					}

					@Override
					public boolean onPrepareActionMode(
							ActionMode paramActionMode, Menu paramMenu) {
						return false;
					}

					@Override
					public void onDestroyActionMode(ActionMode paramActionMode) {
						mCurrentActionMode = null;
					}

					@Override
					public boolean onActionItemClicked(ActionMode mode,
							MenuItem paramItem) {
						final MenuItem item = paramItem;
						switch (item.getItemId()) {
						case R.id.edit_player_name:
							mode.finish();
							showEditPlayerDialog(player);
							return true;
						}
						return false;
					}
				});
		return true;
	}

	public void showEditPlayerDialog(final Player player) {
		final Dialog dialog = new Dialog(getActivity());
		dialog.setContentView(R.layout.edit_player_layout);
		dialog.setTitle(R.string.edit_players_name);
		((EditText) dialog.findViewById(R.id.firstNameInput))
				.setText(player.firstName);
		((EditText) dialog.findViewById(R.id.lastNameInput))
				.setText(player.lastName);

		dialog.findViewById(R.id.playerOK).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						player.firstName = ((EditText) dialog
								.findViewById(R.id.firstNameInput)).getText()
								.toString();
						player.lastName = ((EditText) dialog
								.findViewById(R.id.lastNameInput)).getText()
								.toString();
						((RaterActivity) getActivity()).itemsChanged();
						dialog.dismiss();
					}

				});

		dialog.findViewById(R.id.playerCancel).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						dialog.cancel();
					}
				});
		dialog.show();
	}
}
